<template>
  <div class="content">
    <el-form ref="form" :model="form" label-width="120px" size="mini" :inline="true">
      <el-form-item>
        <el-select v-model="form.schoolId" placeholder="请选择所属学校" size="mini" clearable>
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in schoolList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
        <el-form-item>
          <el-input clearable v-model="form.orgName" size="mini" placeholder="申请单位名称" style="width:150px"></el-input>
        </el-form-item>

      <el-form-item>
        <el-select clearable v-model="form.status" placeholder="请选择状态" size="mini" style="width:150px">
          <el-option label="未提交" value="0"></el-option>
          <el-option label="退款中" value="1"></el-option>
          <el-option label="退款成功" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input clearable v-model="form.createBy" size="mini" placeholder="申请人账号" style="width:150px"></el-input>
      </el-form-item>

      <el-date-picker
        v-model="form.startTime"
        type="datetime"
        size="mini"
        :default-value="new Date()"
        value-format="yyyy-MM-dd HH:mm:ss"
        style="margin-right: 10px;width: 180px;"
        placeholder="选择开始日期">
      </el-date-picker>

      <el-date-picker
        v-model="form.endTime"
        type="datetime"
        :default-value="new Date()"
        value-format="yyyy-MM-dd HH:mm:ss"
        size="mini"
        style="margin-right: 10px;width: 180px!important;"
        placeholder="选择结束日期">
      </el-date-picker>

      <el-button type="primary" size="mini" class="btn" @click="search">
        <i class="fa fa-search" style="margin-right:5px;"></i>查询
      </el-button>
      <br/>
      <el-button
        type="primary"
        size="mini"
        class="btn"
        @click="editAddOrUpdate(1)"
        style="margin-right: 10px;"
      >
        <i class="fa fa-plus" style="margin-right:5px;"></i>新增批量退款
      </el-button>

      <el-button
        type="primary"
        size="mini"
        class="btn"
        @click="excelExport(1)"
        style="margin-right: 10px;"
      >
        <i class="fa fa-bars" style="margin-right:5px;"></i>年级退款汇总表
      </el-button>
    </el-form>

    <!-- <el-divider></el-divider> -->
    <!--detail展示页面-->

    <template>
      <el-table
        :data="tableData"
        :row-key="getRowKeys"
        :expand-row-keys="expands"
        v-loading="loading"
        :lazy="true"
        size="mini"
        height="470"
        style="width: 100%"
      >

        <el-table-column prop="id" label="序号"></el-table-column>
        <el-table-column prop="orgName" label="申请单位名称"></el-table-column>
        <el-table-column prop="code" label="编号"></el-table-column>
        <el-table-column prop="userNum" label="退款人数"></el-table-column>
        <el-table-column prop="countAmont" label="退款金额"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span v-show="scope.row.status==0">未提交</span>
            <span v-show="scope.row.status==1">退款中</span>
            <span v-show="scope.row.status==2">退款成功</span>
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="申请人"></el-table-column>
        <el-table-column prop="createTime" label="申请时间"></el-table-column>

        <el-table-column fixed="right" :label="$t('action.operation')" width="410">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status == 0" size="mini" @click="editAddOrUpdate(2,scope.row.id)">
              <i class="fa fa-edit" style="margin-right:5px;"></i>
              {{$t('action.edit')}}
            </el-button>
            <el-button type="primary" size="mini" v-if="scope.row.status == 0" @click="editStatus(1,scope.row.id)">
              <i class="fa fa-check-square" style="margin-right:5px;"></i>
              提交退款
            </el-button>
            <el-button type="primary" v-if="scope.row.status == 1" size="mini" @click="editStatus(2,scope.row.id)">
              <i class="fa fa-check-square" style="margin-right:5px;"></i>
              确认退款
            </el-button>
            <el-button size="mini" v-if="scope.row.status == 0" type="danger" @click="handleDelete(scope.$index, scope.row)">
              <i class="fa fa-trash" style="margin-right:5px;"></i>
              {{$t('action.delete')}}
            </el-button>

            <el-button type="primary" size="mini" @click="excelExportStudent(scope.row.id)">
              <i class="fa fa-check-square" style="margin-right:5px;"></i>
              操作详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 15, 20,50,100]"
      :page-size="everyPageNum"
      layout="total, sizes,prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!--新增编辑弹框-->
    <el-dialog :title="updateStatus==1?'新增批量退款':'编辑批量退款'" :visible.sync="showEdit" width="60%" v-dialogDrag>
      <GradeClassManagement @hideEdit="hideEditStatus" ref="child" :msg="updateStatus"></GradeClassManagement>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import GradeClassManagement from "@/components/RefundBatch/edit";

export default {
  name: "RefundBatch",
  components: {
    GradeClassManagement
  },
  data() {
    return {
      url: this.$Config.url,
      showEdit: false, //显示编辑弹框
      updateStatus: 1, //默认是新增
      loading: false,
      loading2: false,
      total: 1, //总页数
      everyPageNum: 10, //每页多少条
      currentPage: 1, //当前页
      form: {
        orgName: "",
        status: "",
        createBy:"",
        startTime:"",
        endTime:""
      },
      tableData: [],
      schoolList: [], //学校列表
      everyclass: [], //展开的每个班级
      expands: [],
      gradeId: "",
      expandedRows: "",
      getRowKeys(row) {
        return row.id;
      }
    };
  },
  mounted() {
    this.common();
    this.getSchool();
  },
  methods: {
    handleDelete(index, row) {
      this.$confirm("您确认要删除该退款吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteBranch(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    editStatus(status,id){
      const that = this;
      this.$axios
        .post(
          that.url + "/admin/refundBatch/editStatus",
          that.$qs.stringify({ id: id,status:status }),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.data.code == 200) {
            that.$message({
              type: "success",
              message: "提交成功!"
            });
            that.common(that.currentPage, that.everyPageNum);
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    deleteBranch(id) {
      const that = this;
      this.$axios
        .post(
          that.url + "/admin/refundBatch/delete/{id}",
          that.$qs.stringify({ id }),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.data.code == 200) {
            that.$message({
              type: "success",
              message: "删除成功!"
            });
            that.common(that.currentPage, that.everyPageNum);
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    opeDetail(id){
      alert(id)
    },
    getClass(row, expandedRows) {
      const that = this;
      that.gradeId = row.id;
      that.loading2 = true;
      that.expandedRows = expandedRows;
      if (expandedRows.length) {
        that.expands = [];
        if (row) {
          that.expands.push(row.id); // 每次push进去的是每行的ID
        }
      } else {
        that.expands = []; // 默认不展开
      }

      this.$axios
        .get(that.url + "/admin/student/list", {
          // params: {
          //   gradeId: row.id
          // },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          that.loading2 = false;
          if (res.data.code == 200) {
            that.everyclass = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          that.loading2 = false;
          console.log(error);
        });
    },
    getSchool() {
      const that = this;
      this.$axios
        .get(that.url + "/admin/dept/list", {
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.schoolList = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    changeType() {
      let userType = this.form.userType == "学生" ? 1 : 2;
      this.common(this.currentPage, this.everyPageNum, userType);
    },
    /**
     * 导出
     */
    excelExport(type) {
      let deptIdNew="";
      const that = this;
      var divFrame = window.parent.document.getElementById(
        "downLoadListFrame"
      );
      debugger
      //判断是否存在，如果存在先移除，再重新创建
      if (divFrame != null) {
        window.parent.document.body.removeChild(divFrame);
      }
      var iframe = window.parent.document.createElement("iframe");
      iframe.setAttribute("id", "downLoadListFrame");
      //download_file.id = "downFrame";
      window.parent.document.body.appendChild(iframe);
      divFrame = window.parent.document.getElementById("downLoadListFrame");
      //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
      //divFrame.src = `${this.url}/admin/refundBatch/data/export?deptId=${typeof this.form.schoolId=="object"?this.$Config.dateFormat(this.form.schoolId):this.form.schoolId}&startTime=${typeof this.form.startTime=="object"?this.$Config.dateFormat(this.form.startTime):this.form.startTime}&endTime=${typeof this.form.endTime=="object"?this.$Config.dateFormat(this.form.endTime):this.form.endTime}&userType=${this.form.classStatus}&gradeId=${this.form.glassId}&classId=${this.form.classId}`;
         divFrame.src = `${this.url}/admin/refundBatch/data/export`;
      if(that.form.schoolId){
         divFrame.src += `?deptId=` + that.form.schoolId;
      }else{
        divFrame.src += `?deptId=`;
      }
      if(that.form.orgName != ''){
        divFrame.src += `&orgName=` + that.form.orgName;
      }
      if(that.form.status != ''){
        divFrame.src += `&status=` + that.form.status;
      }
      if(that.form.createBy != ''){
        divFrame.src += `&createBy=` + that.form.createBy;
      }
      if(that.form.startTime != ''){
        divFrame.src += `&startTime=` + that.form.startTime;
      }
      if(that.form.endTime != ''){
        divFrame.src += `&endTime=` + that.form.endTime;
      }

      divFrame.style.display = "none";

    },
   /**
     * 导出
     */
   excelExportStudent(id) {
      let deptIdNew="";
      const that = this;
      var divFrame = window.parent.document.getElementById(
        "downLoadListFrame"
      );
      debugger
      //判断是否存在，如果存在先移除，再重新创建
      if (divFrame != null) {
        window.parent.document.body.removeChild(divFrame);
      }
      var iframe = window.parent.document.createElement("iframe");
      iframe.setAttribute("id", "downLoadListFrame");
      //download_file.id = "downFrame";
      window.parent.document.body.appendChild(iframe);
      divFrame = window.parent.document.getElementById("downLoadListFrame");
      divFrame.src = `${this.url}/admin/refundBatch/student/export?id=`+id;
      divFrame.style.display = "none";

    },
    editAddOrUpdate(status, id) {
      //新增或编辑
      /**
       * 1是新增
       * 2是编辑
       */
      this.showEdit = true;
      if (status == 1) {
        //新增
        this.updateStatus = 1;
        setTimeout(() => {
          this.$refs["child"].resetForm("ruleForm");
        }, 0);
      } else {
        //编辑
        this.updateStatus = 2;
        setTimeout(() => {
          this.$refs["child"].resetData(id);
        }, 0);
      }
    },
    handleSizeChange(val) {
      //   每页多少条
      this.everyPageNum = val;
      this.common(this.currentPage, val);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.common(val, this.everyPageNum);
    },
    hideEditStatus(status) {
      const that = this;
      this.showEdit = false;
      this.common(this.currentPage, this.everyPageNum);
      this.$axios
        .get(that.url + "/admin/class/listBranck", {
          params: {
            gradeId: this.gradeId
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.everyclass = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    search() {
      this.common(this.currentPage, this.everyPageNum, this.form.schoolId);
    },
    common(pageNo = 1, pageSize = 10, deptId = "") {
      const that = this;
      that.loading = true;
      let data={
        pageNo,
        pageSize,
        deptId
      }
      let dataStatus={};
      if(that.form.orgName){dataStatus.orgName=that.form.orgName};
      if(that.form.status){dataStatus.status=that.form.status};
      if(that.form.createBy){dataStatus.createBy=that.form.createBy};
      if(that.form.startTime){dataStatus.startTime=that.form.startTime};
      if(that.form.endTime){dataStatus.endTime=that.form.endTime};

      let requestData={...data,...dataStatus}
      this.$axios
        .get(that.url + "/admin/refundBatch/list", {
          params: requestData,
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          that.loading = false;
          if (res.data.code == 200) {
            that.tableData = res.data.data.records;
            that.total = res.data.data.total;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          that.loading = false;
          console.log(error);
        });
    },
    handleClick(row) {
      console.log(row);
    }
  }
};
</script>

<style scoped lang="scss">
.detail {
  text-align: left;
}

.el-select,
.el-input {
  width: 150px;
}

.el-range-editor--mini.el-input__inner {
  margin-top: 7px;
  margin-right: 10px;
  width: 300px;
}

.el-pagination {
  float: right;
  margin: 20px 10px;
}

.button_list {
  margin-bottom: 10px;
}

.content {
  text-align: left;
}

.el-divider {
  margin: 10px 0;
}

.btn {
  margin-top: 1px;
}

.el-form-item {
  margin-bottom: 0;
}
</style>
